//状态管理，login、register 组件共同维护 is_new 状态
// 当注册成功，跳转到登录状态时，希望能够提示用户
// 使用时在组件中引入即可，如：import store from '../store.js'

export default {
  debug: true,
  state: {
    // is_new: false,
    is_authenticated: window.localStorage.getItem('madblog-token') ? true : false,

    // 从缓存中获取 jwt token，并解析提取其中的用户 ID
    user_id: window.localStorage.getItem('madblog-token') ? JSON.parse(atob(window.localStorage.getItem('madblog-token').split('.')[1])).user_id : 0
    // user_id: window.localStorage.getItem('madblog-token') ? JSON.parse(atob(window.localStorage.getItem('madblog-token').split('.')[1])).user_id : 0
  },
  setNewAction() {
    if (this.debug) {
      console.log('setNewAction triggered')
    }
    this.state.is_new = true
  },
  resetNotNewAction() {
    if (this.debug) {
      console.log('resetNotNewAction triggered')
    }
    this.state.is_new = false
  },

  // 用于维护顶部导航栏登录、登出按钮
  // 当未登录时，显示的登录，登录成功后，显示的是登出
  loginAction() {
    if (this.debug) {
      console.log('loginAction triggered')
    }
    this.state.is_authenticated = true;
    this.state.user_id = JSON.parse(atob(window.localStorage.getItem('madblog-token').split('.')[1])).user_id
  },
  logoutAction() {
    if (this.debug) {
      console.log('logoutAction triggered')
    }
    window.localStorage.removeItem('madblog-token');
    this.state.is_authenticated = false;
    this.state.user_id = 0;
  },
}
